/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.sigawe.SIASDIT.ProgUtama;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sigawe.SIASDIT.dao.db.DBConnection;
import net.sigawe.SIASDIT.dao.impl.InboxDAO;
import net.sigawe.SIASDIT.dao.impl.OutboxDAO;
import net.sigawe.SIASDIT.dao.model.Message;



/**
 *
 * @author yoje
 */
public class Engine implements Runnable {

    private boolean status;
    private Connection connection;
//    private ServiceMessage serviceMessage;

    public Engine() {
        status = true;


        new Thread(this).start();
    }

    public void run() {
        try {
            connection = DBConnection.getInstance().getCon();
            List<Message> listInbox;
            while (true) {
                listInbox = new InboxDAO(connection).getAll();
//                System.out.println(listInbox.size());
                for (Message message : listInbox) {
                    message = new Processor().prosesLayanan(message);
                    if (sendToOutbox(message)) {
                        deleteInbox(message);
                    }
                }
                
                Thread.sleep(300);
                listInbox.clear();
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(Engine.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Engine.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void deleteInbox(Message message) throws SQLException {
//        System.out.println("Engine : deleteInbox...");
        connection = DBConnection.getInstance().getCon();
        new InboxDAO(connection).delete(message.getIdMessage());
    }

    private boolean sendToOutbox(Message message) {
        try {
            connection = DBConnection.getInstance().getCon();
//            System.out.println("Engine : sendToOutbox...");
            System.out.println("Engine : " + message.getText());
            Message msg = new Message();
            msg.setPhoneNumber(message.getPhoneNumber());
            msg.setText(message.getText());
            new OutboxDAO(connection).insert(msg);
            return true;
        } catch (SQLException ex) {
            Logger.getLogger(Engine.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }

        
    }
}
